<?php

namespace Frieza\Modules\Complain\Controllers;

use Biz\pockets\excel\DownExcel;
use Doraemon\model\Member;
use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Admin\Extensions\Tools\UserButton;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Layout\Column;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;
use Doraemon\model\Category;

use Doraemon\model\Complain\Complain as mComplain;
use Doraemon\service\Complain\Complain as sComplain;
use Doraemon\model\Complain\ComplainReply as mComplainReply;

class ComplainController extends Controller
{
    const PAGE_SIZE = 20;

    /**
     * 投诉管理列表
     */
    public function list(Content $content, Request $request)
    {
        $params = [
            'page' => $request->input('page', 1),
            'per_page' => $request->input('per_page', 20),
            'content' => $request->input('content', ''),
            'uid' => $request->input('uid', ''),
            'uname' => $request->input('uname', ''),
            'to_uid' => $request->input('to_uid', ''),
            'to_uname' => $request->input('to_uname', ''),
            'status' => $request->input('status', ''),
            'from' => $request->input('from', ''),
            'phone_type' => $request->input('phone_type', ''),
            'app_ver' => $request->input('app_ver', ''),
            'addtime' => $request->input('addtime', ''),
            'ptype' => $request->input('ptype', ''),
            'type' => $request->input('type', ''),
        ];
        return $content
            ->header('投诉管理')
            ->breadcrumb(
                ['text' => '投诉管理列表', 'url' => '/admin/complain/feedback/list']
            )
            ->body($this->listAction($params));
    }

    /**
     * 投诉管理--信息展示
     */
    private function listAction($params = [])
    {
        $info = sComplain::getList($params);
        $gridModel = new pGridDataModel($info['data'], $info['total'], [
            'perPage' => $params['per_page'],
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($params) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->tools(function ($tools) use ($id) {
                $tools->append("<p class='btn btn-sm btn-success' style='float: right;color:#FFFFFF'><a href='/admin/complain/list/normalword' style='float: right;color:#FFFFFF'><i class='fa fa-flag'>&nbsp;&nbsp;编辑常用语</a></i></p>");
            });
            $grid->tools(function ($tools) use ($params){
                $export_url = http_build_query($params);
                $url = url('/admin/complain/list/export?'.$export_url);
                $button = '<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" title="导出" target="_blank" href="'.$url.'"><i class="fa fa-download"></i><span class="hidden-xs"> 导出</span></a></div>';
                $tools->append($button);
            });

            // 筛选项
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();

                $filter->column(1 / 2, function ($filter) {
                    $filter->dropDown('id', [
                        'content' => '关键词',
                        'uid' => '用户uid',
                        'uname' => '用户昵称',
                        'to_uid' => '被举报用户uid',
                        'to_uname' => '被举报用户昵称',
                    ]);
                    $filter->in('from', '来源')->radio(mComplain::FROM_OPTIONS)->default('all');
                    $filter->in('status', '状态')->radio(mComplain::STATUS)->default('all');
                    $filter->in('phone_type', '系统类型')->radio(mComplain::CLIENT_TYPE)->default('all');
                    $filter->equal('app_ver', '系统版本')->select(sComplain::listVersionByPhoneType())->default('all');
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('type', '类型')->select(mComplain::TYPENAME);
                    $filter->between('addtime', '时间')->datetime();
                });
            });

            $grid->column('id')->width(40);
            $grid->column('type_name', '类型')->width(80);
            $grid->column('用户')->display(function () {
                $userArr = $this->user;
                $userStr = "<a href='/admin/user/Detail/{$userArr['uid']}' target='_blank'><i class='fa fa-user fa-fw'></i>{$userArr['nick']}({$userArr['uid']})</a><br>";
                $userStr .= "手机类型：$this->android_phone <br>";
                $userStr .= "手机型号:  $this->phone_type $this->phone_ver <br>";
                $userStr .= "应用版本: $this->app_ver <br>";
                $userStr .= "用户身份: " . Member::$typeDesc[$userArr['type']];
                return $userStr;
            })->width(280);
            $grid->column('force_user', '被举报用户')->display(function () {
                $forceUserArr = $this->force_user;
                $forceUserStr = "<a href='/admin/user/Detail/{$forceUserArr['uid']}' target='_blank'><i class='fa fa-user fa-fw'></i>{$forceUserArr['nick']}({$forceUserArr['uid']})</a><br>";
                $forceUserStr .= "用户身份: " . Member::$typeDesc[$forceUserArr['type']];
                return $forceUserStr;
            })->width(150);
            $grid->column('from', '所在页')->display(function () {
                return $this->from;
            })->width(100);
            $grid->column('commentShow', '被举报评论内容')->display(function () {
                return $this->commentShow;
            })->width(400);
            $grid->column('内容')->display(function () {
                return $this->date . ":<br />" . $this->message;
            })->width(400);
            $grid->column('handle_message', '备注')->editable()->width(200);
            $grid->column('status', '状态')->label([
                '未处理' => 'warning',
                '已回复' => 'success',
            ]);
            $grid->column('操作')->display(function () {
                $userArr = $this->user;
                $lastTime = $this->lastReplyTime;
                if (!empty($lastTime)) {
                    $str = "回复时间：<br />" . date("Y-m-d H:m;s", $lastTime);
                } else {
                    $str = '未回复';
                }
                return $str . '<br />
                <a href="/admin/complain/list/' . $userArr['uid'] . "/handle/" . $this->id . '" target="_blank"><i class="fa fa-cog fa-spin"></i>处理</a><br />
                ';
            })->width(200);
        });

        return $listGrid->render();
    }

    /**
     * 投诉处理
     */
    public function handleComplain($uid = 0, $complainId = 0, Request $request, Content $content)
    {
        return $content
            ->header('投诉处理')
            ->breadcrumb(
                [
                    'text' => '投诉管理列表',
                    'url' => '/complain/list'
                ],
                ['text' => "投诉编辑"]
            )
            ->row(function (Row $row) use ($uid, $complainId) {
                $row->column(6, function (Column $column) use ($uid, $complainId) {
                    $column->row($this->handleComplainList($uid, $complainId));
                    $column->row($this->handleComplainforceList($uid, $complainId));
                });
                $row->column(6, $this->handleComplainForm($uid, $complainId));
            });
    }

    /**
     * 投诉处理--举报人信息
     */
    private function handleComplainList($uid, $complainId)
    {
        $info = sComplain::handleComplain($uid, $complainId);
        $gridModel = new pGridDataModel($info['contentList']);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($info) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->disableFilter();
            $grid->tools(function ($tools) use ($id) {

                // $tools->append("<p class='btn btn-sm btn-success' style='float: right;color:#FFFFFF'><a href='/admin/complain/list/normalword' style='float: right;color:#FFFFFF'><i class='fa fa-flag'>&nbsp;&nbsp;编辑常用语</a></i></p>");

            });
            $grid->disablePagination();
            $strTitle = '举报人:' . $info['userInfo'];
            $grid->column('message', $strTitle)->display(function () {
                return $this->message;
            });
        });

        return $listGrid;
    }

    /**
     * 投诉处理--被举报人信息
     */
    private function handleComplainforceList($uid, $complainId)
    {
        $info = sComplain::handleComplain($uid, $complainId, 1);
        $gridModel = new pGridDataModel($info['forceList']);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($info) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->disableFilter();
            $grid->disablePagination();
            $strTitle = '被举报人:' . $info['forceUserInfo'];
            $grid->column('message', $strTitle)->display(function () {
                return $this->message;
            });
        });

        return $listGrid;
    }

    /**
     * 投诉处理--投诉信息填写
     */
    private function handleComplainForm($uid, $complainId)
    {
        $this->wordChoose();
        $info = sComplain::handleComplain($uid, $complainId);
        $word = sComplain::getNormalWord();
        $form = new Form($info);

        $form->display('userInfo', '用户');
        $options = $info['replyUserSelect'];
        $form->radio('replyUserId', '回复对象')->options($options)->default($info['user']['uid']);
        $form->text('title', '标题：');
        $form->textarea('message', '消息：');
        $states = [
            'on' => ['value' => 1, 'text' => '是', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '否', 'color' => 'danger'],
        ];
        $form->checkbox('link', '是否跳转')->options(['1' => '本条消息可跳转社区规范']);
        $form->select('normalword', '常用语：')->options($word)->default('-1');
        $form->action("/admin/complain/list/handle/save/$uid/$complainId");
        return $form->render();
    }

    /**
     * 投诉处理--保存投诉信息
     */
    public function saveHandleComplain($uid, $complainId, Request $request)
    {
        $params = [
            'title' => $request->input('title', ''),
            'content' => $request->input('message', ''),
            'link' => $request->input('link', 0),
            'normalword' => $request->input('normalword', ''),
            'replyUserId' => $request->input('replyUserId', ''),
        ];
        $result = sComplain::saveHandleComplain($uid, $complainId, $params);
        if ($result['code']) {
            $success = new MessageBag([
                'title' => $result['message'],
            ]);
            return back()->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => $result['message'],
            ]);

            return back()->with(compact('error'));
        }

    }

    /**
     * 投诉处理--备注信息保存
     */
    public function saveRemarksHandleComplain($complainId, Request $request)
    {
        $params = [
            'handle_message' => $request->input('value', ''),
            'handle_time' => time(),
            'handle_uid' => Admin::user()->id,
        ];

        $result = sComplain::saveRemarksHandleComplain($complainId, $params);

        if ($result) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        } else {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);

            return back()->with(compact('error'));
        }

    }

    /**
     * 常用语编辑
     */
    public function editNormalWord(Content $content)
    {
        $tab = new Tab();
        $tab->add("常用语编辑", $this->editNormalWordAction());
        return $content
            ->header('反馈管理')
            ->breadcrumb(
                [
                    'text' => '投诉管理列表',
                    'url' => '/complain/list'
                ],
                ['text' => "常用语编辑"]
            )
            ->body($tab);
    }

    /**
     * 常用语编辑--信息展示
     */
    private function editNormalWordAction()
    {
        $info = sComplain::editNormalWord();
        $form = new Form($info);
        $form->textarea('text', '常用语')->help('请用换行隔开每条常用语');
        $form->action('/admin/complain/list/normalword/save');
        return $form->render();
    }

    /**
     * 常用语编辑--信息保存
     */
    public function saveNormalWord(Request $request)
    {
        $text = $request->input('text', '');
        $result = sComplain::editNormalWord($text);

        if ($result) {
            return back()->with('success', new MessageBag([
                'title' => '操作成功'
            ]));
        } else {
            return back()->with('error', new MessageBag([
                'title' => '操作失败'
            ]));
        }
    }

    public function export(Request $request)
    {
        $params = [
            'content' => $request->input('content', ''),
            'uid' => $request->input('uid', ''),
            'uname' => $request->input('uname', ''),
            'to_uid' => $request->input('to_uid', ''),
            'to_uname' => $request->input('to_uname', ''),
            'status' => $request->input('status', ''),
            'from' => $request->input('from', ''),
            'phone_type' => $request->input('phone_type', ''),
            'app_ver' => $request->input('app_ver', ''),
            'addtime' => $request->input('addtime', ''),
            'ptype' => $request->input('ptype', ''),
            'type' => $request->input('type', ''),
        ];

        //导出符合筛选的所有数据
        $params['page'] = 1;
        $params['per_page'] = PHP_INT_MAX;

        $info = sComplain::getExportList($params);
        $res = [];
        if (!empty($info['data'])) {
            foreach ($info['data'] as $k => $v) {
                $android_phone = empty($v['android_phone']) ? '' : $v['android_phone'];
                $userType = Member::$typeDesc[$v['user']['type']];
                $forceUserType = Member::$typeDesc[$v['force_user']['type']];
                $res[$k]['type_name'] = $v['type_name'];
                $res[$k]['uid'] = $v['user']['uid'];
                $res[$k]['user_name'] = $v['user']['nick'];
                $res[$k]['user_type'] = $userType;
                $res[$k]['force_uid'] = $v['force_user']['uid'];
                $res[$k]['force_user_name'] = $v['force_user']['nick'];
                $res[$k]['force_user_type'] = $forceUserType;
                $res[$k]['force_type_name'] = $v['from']['name'];
                $res[$k]['force_type_value'] = strlen($v['from']['value']) == 16 ? $v['from']['value'] : '';
                $res[$k]['commentShow'] = $v['commentShow'];
                $res[$k]['content'] = self::filterEmoji($v['message']);
                $res[$k]['date'] = $v['date'];
            }
        }
        if(empty($res)){
            $error = new MessageBag([
                'title' => '没有数据',
            ]);
            return back()->with(compact('error'));
        }
        $reason = "投诉管理";
        $header = ["类型", "举报用户uid", "举报用户昵称", "举报用户身份", "被举报用户uid", "被举报用户昵称", "被举报用户身份", "举报内容（所在页）", "举报内容ID", "被举报评论内容", "举报原因（内容）", "举报时间"];
        $excelObj = new DownExcel();
        $excelObj->setFileName($reason);
        $excelObj->setSheetTitle($reason);
        //设置列宽
        $widths = ['A' => 10, 'B' => 15,'H' => 15,'I' => 30,'J' => 15,'K' => 30,'L' => 30];
        $excelObj->setWidth($widths);
        //默认单元格居中
        $excelObj->setDefaultStyleAlignment();
        $excelObj->freezePane('A1');//冻结窗口
        $excelObj->setTextFormat('A');
        $excelObj->setTextFormat('B');
        $excelObj->create($res, $header);

    }

    private function wordChoose()
    {
        Admin::script(
            <<<SCRIPT
            $('.normalword').on('change',function(){
            var option =$(this).find("option:selected").text();
            var message=  $(".message").val();
            $(".message").val(message+option);       
         });
SCRIPT
        );
    }


    private static function filterEmoji($str)
    {
        $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;
    }

}
